<script>
export default {
  data() {
    return {
      title: '',
      message: '',
      showCloseBtn: true,
      show: true,
      closeOnClickModal: true,
    }
  },
  mounted() {
    console.log('messagebox mounted');
    this.initEventListner()
  },
  beforeDestroy() {
  },
  methods: {
    initEventListner() {
      console.log('初始化事件监听');
      this.$refs.messageBox.addEventListener('click', (e) => {
        e.stopPropagation()
      })

      if (this.closeOnClickModal) {
        console.log('遮罩注册 click 事件');
        this.$refs.messageBoxWrapper.addEventListener('click', this.handleClose)
      }
    },
    handleClose(e) {
      if (this.closeOnClickModal) {
        this.$refs.messageBoxWrapper.removeEventListener('click', this.handleClose)
      }
      this.show = false
      this.$nextTick(() => {
        this.$emit('doClose')
      })
    },
    confirm() {
      throw new Error('请实现 confirm 方法')
    },
    cancel() {
      throw new Error('请实现 cancel 方法')
    }
  }
}
</script>

<template>
  <transition name="fade">
    <template v-if="show">
      <div ref="messageBoxWrapper" class="message-box__wrapper fixed top-0 left-0 right-0 bottom-0 text-center">
        <div ref="messageBox" key="info" class="message-box bg-white">
          <div class="message-box__header">
            <div class="message-box__title">
              <span>{{ title }}</span>
            </div>
            <button v-if="showCloseBtn" title="关闭" class="message-box__headerbtn" @click="handleClose">×</button>
          </div>
          <div class="message-box__content">
            {{ message }}
          </div>
          <div class="message-box__footer">
            <button class="message-box__footer-btn" @click="confirm">确 定</button>
            <button class="message-box__footer-btn" @click="cancel">取 消</button>
          </div>
        </div>
      </div>
    </template>
  </transition>
</template>

<style scoped>
.message-box__wrapper {
  z-index: 11;
}

.message-box__wrapper::after {
  content: '';
  display: inline-block;
  width: 0;
  height: 100%;
  vertical-align: middle;
}

.message-box {
  display: inline-block;
  vertical-align: middle;
  width: 420px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  opacity: 1;
  z-index: 69;
  background: #fff;
}

.message-box__header,
.message-box__content,
.message-box__footer {
  padding: 7px 10px;
}

.message-box__header {
  position: relative;
}

.message-box__headerbtn {
  position: absolute;
  top: 7px;
  right: 10px;
}

.message-box__footer-btn {
  border: 1px solid #DCDFE6;
  padding: 3px 7px;
  background-color: #fff;
  color: #606266;
  border-radius: 4px;
  transition: 0.1s;
}

.message-box__footer-btn:hover {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.message-box__footer-btn:not(:first-of-type) {
  margin-left: 5px;
}
</style>
